package com.example.peibei.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dingtao.common.bean.Dynamic;
import com.dingtao.common.bean.SquareDetail;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDFragment;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.ImageViewInfo;
import com.example.peibei.service.presenter.DynamicPresenter;
import com.example.peibei.service.presenter.FollowPresenter;
import com.example.peibei.service.presenter.FollowSquareDetailPresenter;
import com.example.peibei.service.presenter.GiveUpPresenter;
import com.example.peibei.service.presenter.SquareDetailListPresenter;
import com.example.peibei.ui.activity.DynamicDetailActivityTwo;
import com.example.peibei.ui.activity.PersonInfoActivityTwo;
import com.example.peibei.ui.activity.SquareDetailActivityTwo;
import com.example.peibei.ui.adapter.DynamicListAdapter;
import com.example.peibei.ui.adapter.SquareDetailListAdapter;
import com.example.peibei.ui.weight.EmptyRecyclerView;
import com.example.peibei.ui.weight.ImagePreviewLoader;
import com.previewlibrary.GPreviewBuilder;
import com.previewlibrary.ZoomMediaLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 动态列表
 */
public class SquareDetailListFragment extends WDFragment {

    @BindView(R.id.rv_dynamic_list)
    EmptyRecyclerView orderList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty_view)
    LinearLayout empty_view;

    String squareId = "";
    String type = "";
    List<SquareDetail.RecordsDTO> dynamics;
    private SquareDetailListAdapter dynamicListAdapter;
    private SquareDetailListPresenter dynamicPresenter;
    private FollowSquareDetailPresenter followPresenter;
    private SPUtils spUtils;
    private String token;
    private int updatePosition;
    private List<ImageViewInfo> stringList = new ArrayList<>();

    public SquareDetailListFragment(String squareId, String type) {
        this.squareId = squareId;
        this.type = type;
    }

    @Override
    public String getPageName() {
        return "动态列表fragment";
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dynamic_list;
    }

    @Override
    protected void initView() {
        dynamics = new ArrayList<>();
        orderList.setLayoutManager(new LinearLayoutManager(getContext()));
        dynamicListAdapter = new SquareDetailListAdapter(dynamics);
        orderList.setAdapter(dynamicListAdapter);
        orderList.setEmptyView(empty_view);
        spUtils = new SPUtils(getActivity(), SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
//        orderList.setLoadingListener(this);
        ZoomMediaLoader.getInstance().init(new ImagePreviewLoader());
        //获取数据
        dynamicPresenter = new SquareDetailListPresenter(new OrderCall());
        followPresenter = new FollowSquareDetailPresenter(new FollowCall());
//        dynamicPresenter.reqeust(true, type, squareId, "Bearer " + token);
        refreshLayout.setOnRefreshListener(refreshLayout -> onRefreshStart());
        refreshLayout.setOnLoadMoreListener(refreshLayout -> onLoadMoreStart());
        dynamicListAdapter.addChildClickViewIds(R.id.zan_ly, R.id.iv_head, R.id.iv_img_one, R.id.iv_img_two_dynamic, R.id.iv_img_three, R.id.iv_img_four);
        dynamicListAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.zan_ly) {
                    updatePosition = position;
                    SquareDetail.RecordsDTO item = (SquareDetail.RecordsDTO) adapter.getData().get(position);
                    boolean follow = item.isFollow();
                    int isFollow;
                    if (!follow) {
                        isFollow = 0;
                    } else {
                        isFollow = 1;
                    }
                    String id = item.getId();
                    followPresenter.reqeust(isFollow, "Bearer " + token, id);
                } else if (view.getId() == R.id.iv_head) {
                    SquareDetail.RecordsDTO order = (SquareDetail.RecordsDTO) adapter.getData().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putString("mid", order.getMid() + "");
                    intent(PersonInfoActivityTwo.class, bundle);
                } else if (view.getId() == R.id.iv_img_one || view.getId() == R.id.iv_img_four) {
                    stringList.clear();
                    SquareDetail.RecordsDTO order = (SquareDetail.RecordsDTO) adapter.getData().get(position);
                    List<String> imgUrls = order.getImgUrls();
                    loadImages(imgUrls, 0);
                } else if (view.getId() == R.id.iv_img_two_dynamic) {
                    stringList.clear();
                    SquareDetail.RecordsDTO order = (SquareDetail.RecordsDTO) adapter.getData().get(position);
                    List<String> imgUrls = order.getImgUrls();
                    loadImages(imgUrls, 1);
                } else if (view.getId() == R.id.iv_img_three) {
                    stringList.clear();
                    SquareDetail.RecordsDTO order = (SquareDetail.RecordsDTO) adapter.getData().get(position);
                    List<String> imgUrls = order.getImgUrls();
                    loadImages(imgUrls, 2);
                }
            }
        });
        dynamicListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                SquareDetail.RecordsDTO item = (SquareDetail.RecordsDTO) adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putString("subjectId", item.getId() + "");
                intent(SquareDetailActivityTwo.class, bundle);
            }
        });
    }

    private void loadImages(List<String> item, int position) {
        if (item != null && item.size() > 0) {
            for (int i = 0; i < item.size(); i++) {
                if (!TextUtils.isEmpty(item.get(i))) {
                    stringList.add(new ImageViewInfo(item.get(i)));
                }
            }
            //图片预览（关键
            GPreviewBuilder.from(getActivity())
                    .setData(stringList)  //数据
                    .setCurrentIndex(position)  //图片下标
                    .setSingleFling(true)  //是否在黑屏区域点击返回
                    .setDrag(false)  //是否禁用图片拖拽返回
                    .setType(GPreviewBuilder.IndicatorType.Number)  //指示器类型
                    .start();  //启动
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        token = spUtils.getString(SpConstant.USER_TOKEN);
        onRefreshStart();
    }

    public void onRefreshStart() {
        if (dynamicPresenter.isRunning()) {
            refreshLayout.finishRefresh();
            return;
        }
        dynamicPresenter.reqeust(true, type, squareId, "Bearer " + token);
    }

    public void onLoadMoreStart() {
        if (dynamicPresenter.isRunning()) {
            refreshLayout.finishLoadMore();
            return;
        }
        dynamicPresenter.reqeust(true, type, squareId, "Bearer " + token);
    }

    class OrderCall implements DataCall<SquareDetail> {

        @Override
        public void success(SquareDetail data, Object... args) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            //添加列表并刷新
            if (dynamicPresenter.getPage() == 1) {
                dynamics.clear();
            }
            dynamics.addAll(data.getRecords());
//            dynamicListAdapter.setNewInstance(data.getRecords());
            dynamicListAdapter.notifyDataSetChanged();
        }

        @Override
        public void fail(ApiException e, Object... args) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
    }

    class FollowCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            //还需要刷新处理
//            Dynamic.RecordsDTO recordsDTO = dynamicListAdapter.getData().get(updatePosition);
            SquareDetail.RecordsDTO recordsDTO = dynamics.get(updatePosition);
            int follow = recordsDTO.getFollowerCount();
            boolean dianzan = recordsDTO.isFollow();
            recordsDTO.setFollow(!dianzan);
            recordsDTO.setFollowerCount(!dianzan ? follow + 1 : follow - 1);
            dynamicListAdapter.notifyDataSetChanged();
//            dynamicListAdapter.notifyItemChanged(updatePosition);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
    }


}
